import 'package:FineArt/constants.dart';
import 'package:FineArt/core/api/class_api.dart';
import 'package:FineArt/core/utils/toast.dart';
import 'package:FineArt/core/widget/grid/grid_item_video.dart';
import 'package:FineArt/core/widget/list/notice_item.dart';
import 'package:FineArt/page/my/createclass.dart';
import 'package:FineArt/page/my/selectstudent.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:FineArt/utils/sputils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import 'contacts_list_page.dart';
import 'package:FineArt/core/utils/event.dart';
import 'package:FineArt/components/CustomDialog.dart';
//班级成员
class ClassDetailPage extends StatefulWidget {
  TeacherClassesEntity entity;

  ClassDetailPage(this.entity);

  @override
  State<StatefulWidget> createState() {
    return _ClassDetailPageState();
  }
}

class _ClassDetailPageState extends State<ClassDetailPage> {
  List resources = [6];
  TeacherClassesEntity _entity;
  var _eventBusListener;
  @override
  void initState() {
    super.initState();
    _entity = widget.entity;
    _loadStudent();
    _eventBusListener= XEvent.on("refreshClassDetail",(index){
      LogUtil.d("_eventBus>> $index");
      _loadStudent();
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    LogUtil.d("didChangeDependencies>>>>>>>>>>>>");
  }

  @override
  void dispose() {
    XEvent.cancel("refreshClassDetail",_eventBusListener);
    super.dispose();
  }
  List<Student> data = [];

  _loadStudent() {
    int uid = _entity.classId;
    ClassApi().studentList(uid).then((res) {
      if (res.code == 200) {
        setState(() {
          data = res.data;
          data.add(Student(name: "", uid: -1));
          data.add(Student(name: "", uid: -2));
        });
      } else {
        ToastUtils.toast("获取学生出错${res.msg}");
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        // backgroundColor: category_bg_unselected,
        backgroundColor: Colors.white,
        appBar: AppBar(
            title: Text(
              _entity.className,
              style: TextStyle(color: text_black, fontSize: setSp(18)),
            ),
            centerTitle: true,
            elevation: 0,
            backgroundColor: Colors.white,
            brightness: Brightness.light,
            toolbarHeight: getPortraitSHeight(40),
            leading: IconButton(
                alignment: Alignment.centerLeft,
                icon: Image.asset(
                  "assets/images/icon_back_black.png",
                  width: getPortraitSWidth(11),
                  height: getPortraitSHeight(18),
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                })),
        body: SafeArea(
          child: _grid_list(),
        ));
  }

  EasyRefreshController _controller = EasyRefreshController();

  Widget _grid_list() {
    double width = MediaQuery.of(context).size.width * 0.98;
    MaterialHeader header =
        MaterialHeader(completeDuration: new Duration(milliseconds: 100));
    return CustomScrollView(slivers: [
      SliverPadding(
        padding: EdgeInsets.symmetric(
            vertical: getPortraitSHeight(16.5),
            horizontal: getPortraitSWidth(12.5)),
        sliver: SliverGrid(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 5,
            mainAxisSpacing: 3,
            crossAxisSpacing: 0,
            childAspectRatio: 1,
          ),
          delegate: SliverChildBuilderDelegate(
            (BuildContext context, int index) {
              //创建子widget
              var resource = data[index];
              return buildStudentItem(resource, index);
            },
            childCount: data.length,
          ),
        ),
      ),
      SliverToBoxAdapter(
        child: Container(
          color: category_bg_unselected,
          child: Column(
            children: [
              buildRightArrow(_entity.className, "班级名称", () {
                Navigator.of(context).push(MaterialPageRoute(builder: (context){
                  return CreateClassPage(classesEntity:widget.entity);
                }));
              }),
              buildRightArrow("", "班主任转让", () {
                Navigator.of(context).push(MaterialPageRoute(builder: (context){
                  return ContactListPage(type:2, classesEntity:widget.entity);
                }));
              }),
              buildQuitClass(),
            ],
          ),
        ),
      )
    ]);
    //=====列表=====//
  }

  Widget buildStudentItem(Student student, int index) {
    return InkWell(
      child: Container(
          color: Colors.white,
          child: Column(
            children: [
              Container(
                decoration: BoxDecoration(
                  color: bg_icon_gray,
                  borderRadius: BorderRadius.all(Radius.circular(4.0)),
                ),
                child: getPhoto(student, index),
                width: getPortraitSWidth(50),
                height: getPortraitSHeight(50),
              ),
              SizedBox(
                width: getPortraitSWidth(0.5),
              ),
              Text(
                student.name,
                style: TextStyle(fontSize: setSp(12), color: text_black),
              ),
            ],
          )),
      onTap: () {
        if(student.uid==-1){
          Navigator.of(context).push(MaterialPageRoute(builder: (context){
            return ContactListPage(type:0, classesEntity:widget.entity);
          }));
        }
        else if(student.uid==-2){///移除
          Navigator.of(context).push(MaterialPageRoute(builder: (context){
            return ContactListPage(type:1, studentList:data,classesEntity:widget.entity);
          }));
        }
        else{

        }
        LogUtil.d("class click $index");
      },
    );
  }

  Widget getPhoto(Student student, int index){
    if(student.uid==-1){
      return Image.asset("assets/images/icon_add_black.png",fit: BoxFit.cover,);
    }
    else if(student.uid==-2){
      return Image.asset("assets/images/icon_subtrac_black.png",fit: BoxFit.cover,);
    }
    else{
      return Image.network(
        student.portrait,
        fit: BoxFit.cover,
        width: getPortraitSWidth(50),
        height: getPortraitSHeight(50),
      );
    }
  }
  Widget buildQuitClass() {
    return InkWell(
      onTap: () {
        leaveClassConfirm();
      },
      child: Container(
        width: SizeConfig.screenWidth * 0.9,
        height: getPortraitSHeight(50),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: red_main,
            borderRadius: BorderRadius.all(Radius.circular(25))),
        margin: EdgeInsets.only(top: getPortraitSHeight(20)),
        child: Text(
          "退出班级",
          style: TextStyle(color: Colors.white, fontSize: 15),
        ),
      ),
    );
  }
  void leaveClassConfirm() {
    showDialog(
        context: context,
        builder: (context) {
          return CustomDialog(
              content: "确认要退出班级吗?",
              enterTxt: "确认",
              callback: (res0) {
                LogUtil.d("customerDialog exitClass Sure>>>>>>>>>>>>>>>>>");

              }
          );
        }
    );

  }
  Widget buildRightArrow(String className, String name, function) {
    return InkWell(
      child: Container(
        color: Colors.white,
        height: getPortraitSHeight(58.5),
        margin: EdgeInsets.only(top: getPortraitSHeight(10)),
        padding: EdgeInsets.symmetric(horizontal: getPortraitSWidth(20)),
        child: Row(
          children: [
            Text(
              name,
              style: TextStyle(fontSize: setSp(15), color: text_black),
            ),
            Expanded(child: Text("")),
            Text(
              className,
              style: TextStyle(fontSize: setSp(15), color: text_black),
            ),
            SizedBox(
              width: getPortraitSWidth(5),
            ),
            Image.asset(
              "assets/images/icon_right_arrow.png",
              width: getPortraitSWidth(8),
              height: getPortraitSHeight(16),
            ),
          ],
        ),
      ),
      onTap: function,
    );
  }
}
